﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;

namespace Affinity.Synthesis
{
    internal static class LambdaBindingTargetManager
    {
        public static TReturn BindLambda<TReturn>(this object target, string propertyName, Expression<Func<TReturn>> lambdaExpression, TReturn defaultValue)
        {   
            LambdaBindingTarget lambdaBindingTarget;

            lock (_lambdaBindingTargetsLock)
            {
                if (!_lambdaBindingTargets.TryGetValue(target, out lambdaBindingTarget))
                {
                    lambdaBindingTarget = new LambdaBindingTarget(target);
                    _lambdaBindingTargets.Add(target, lambdaBindingTarget);
                }
            }

            return lambdaBindingTarget.BindLambda<TReturn>(propertyName, lambdaExpression, defaultValue);
        }
        
        
        #region Private Implementation

        private static readonly ConditionalWeakTable<object, LambdaBindingTarget> _lambdaBindingTargets = new ConditionalWeakTable<object,LambdaBindingTarget>();
        private static readonly object _lambdaBindingTargetsLock = new object();

        #endregion
    }
}
